﻿using AutoMapper;
using BasicInformation.ApiWrite.Application.Command.Carrier;
using BasicInformation.Domain;
using BasicInformation.ErrorCode;
using BasicInformation.Infrastructure.Implement;
using MediatR;

namespace BasicInformation.ApiWrite.Application.Handler.Carrier
{
    public class AddCarrierHandler : IRequestHandler<AddCarrierCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<AddCarrierHandler> logger;
        private readonly IMapper mapper;

        public AddCarrierHandler(DatabaseContext db,ILogger<AddCarrierHandler> logger,IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddCarrierCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var carrier=mapper.Map<CarrierModel>(request);
            var model = db.SqlSugar.Queryable<CarrierModel>().Where(x=>x.CarrierCode==request.CarrierCode).Count();
            if (model>0)
            {
                result.Msg = "该承运商管理已存在，请重新输入";
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
                return await Task.FromResult(result);
            }
            //if (!string.IsNullOrEmpty(request.CarrierName))
            //{
            //    result.Msg = "承运商名称不能为空，请重新输入";
            //    result.Code = ApiEnum.Fail;
            //    logger.LogError(result.Msg);
            //    return await Task.FromResult(result);
            //}

            

            int r = await db.SqlSugar.Insertable(carrier).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "承运商管理添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg = "承运商管理添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
